import org.junit.Test;

public class Solution {
    @Test
    public void testCon(){
        ListNode node1 = new ListNode(1);
        ListNode node2 = new ListNode(2);
        ListNode node3 = new ListNode(3);
        ListNode node4 = new ListNode(4);
        ListNode node5 = new ListNode(5);
        node1.next=node2;
        node2.next=node3;
        node3.next=node4;
        node4.next=node5;

        reverseKGroup(node1, 2);
    }


    public ListNode reverseKGroup(ListNode head, int k) {
        int curIndex=k-1;
        ListNode p=head;
        ListNode q=head;
        ListNode curHead=head;
        boolean flag=false;
        while(p!=null){
            p=p.next;
            curIndex--;
            if(curIndex==0){
                curIndex=k-1;
                ListNode temp=p;
                if(!flag){
                    flag=true;
                    head=p;
                }
                while(curIndex>0){
                    curIndex--;
                    q.next=temp.next;
                    temp.next=q;
                    q=curHead.next;
                    curHead=curHead.next;
                    //temp=temp.next;

                }
                q.next=curHead;
                curIndex=k-1;
                curHead=p;
                p=q.next;
                q=q.next;
            }
        }
        return head;
    }
}
class  ListNode{
    ListNode next;
    Integer val;

    public ListNode(Integer val) {

        this.val = val;
    }
}